#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <memory>
#include <unistd.h>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "InetAddr.hpp"
// #include "ThreadPool.hpp"

class TcpSocket;
using namespace log_ns;
using SockSPtr = std::shared_ptr<TcpSocket>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERR
};

static int g_back_log = 8;

class socket
{
public:
    virtual void createSocket() = 0;
    virtual void bindSocket(uint16_t port) = 0;
    virtual void listenSocket(int gblcklog = g_back_log) = 0;
    virtual SockSPtr acceptSocket(InetAddr *cliaddr) = 0;
    virtual bool connectSocket(const std::string& peerip, uint16_t peerport) = 0;
    virtual int Sockfd() = 0;
    virtual ssize_t Recv(std::string *out) = 0;
    virtual ssize_t Send(const std::string &in) = 0;

public:
    void buildListenSocket(uint16_t port)
    {
        createSocket();
        bindSocket(port);
        listenSocket();
    }
    bool buildClientSocket(const std::string& peerip, uint16_t peerport)
    {
        createSocket();
        return connectSocket(peerip, peerport);
    }
};

class TcpSocket : public socket
{
private:
    int _sockfd;

public:
    TcpSocket()
    {
    }
    TcpSocket(int sockfd) : _sockfd(sockfd)
    {
    }
    ~TcpSocket()
    {
        close(_sockfd);
    }
    void createSocket() override
    {
        // 1. 创建socket
        _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket create error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _sockfd); // 3
    }
    void bindSocket(uint16_t port) override
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        // 2. bind sockfd 和 Socket addr
        if (::bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success, sockfd: %d\n", _sockfd); // 3
    }
    void listenSocket(int gblcklog) override
    {
        // 3. 因为tcp是面向连接的，tcp需要未来不断地能够做到获取连接
        if (::listen(_sockfd, gblcklog) < 0)
        {
            LOG(FATAL, "listen error\n");
            exit(LISTEN_ERR);
        }
        LOG(INFO, "listen success\n");
    }
    SockSPtr acceptSocket(InetAddr *cliaddr) override
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        // 4. 获取新连接
        int sockfd = ::accept(_sockfd, (struct sockaddr *)&client, &len);
        if (sockfd < 0)
        {
            LOG(WARNING, "accept error\n");
            return nullptr;
        }
        *cliaddr = InetAddr(client);
        LOG(INFO, "get a new link, client info : %s, sockfd is : %d\n", cliaddr->AddrStr().c_str(), sockfd);
        return std::make_shared<TcpSocket>(sockfd); // C++14
    }
    bool connectSocket(const std::string& peerip, uint16_t peerport) override
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(peerport);
        ::inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

        int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            return false;
        }
        return true;
    }
    int Sockfd()
    {
        return _sockfd;
    }
    ssize_t Recv(std::string *out) override
    {
        char inbuffer[4096];
        ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
        if (n > 0)
        {
            inbuffer[n] = 0;
            *out += inbuffer;
        }
        return n;
    }
    ssize_t Send(const std::string &in) override
    {
        return ::send(_sockfd, in.c_str(), in.size(), 0);
    }
    void Close()
    {
        close(_sockfd);
    }
};